
import count from '@dfeidao/atom-nodejs/db/count';
import query from '@dfeidao/atom-nodejs/db/query';
import format from '@dfeidao/atom-nodejs/dt/format';
// import { systemid } from './config';
interface Message {
	productid: string;
	role_name: string;
	page_size: number;
	page_no: number;
}

interface ManagementSanitation {
	_id: string;
	create_time: number;
	icon: string;
	role_type_id: string;
	role_type_name: string;
	productid: string;
	role_name: string;
}

export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	const systemid = '12';

	const { exec, prepare } = query(action_id, session_id, systemid);
	const filter = {} as { productid: string; role_name: {}; };
	const productid = msg.productid;
	if (productid) {
		filter.productid = productid;
	}
	const role_name = msg.role_name;
	if (role_name) {
		filter.role_name = { $like: `%${role_name}%` };
	}
	prepare('pub_role', ['role_no', 'role_name', 'role_type_id', 'create_time', 'icon', 'productid'], filter, msg.page_size, msg.page_no, [], []);
	const [data] = await exec<ManagementSanitation>();
	const arr = data.map((v) => {
		return v.role_type_id;
	});

	prepare('pub_role_type', ['role_type_name'], { productid, _id: { $in: arr } }, 199, 1, [], []);
	const [data1] = await exec<ManagementSanitation>();

	const dt = data.map((item) => {
		const role_type_id1 = item.role_type_id;
		const ck_data = data1.filter((d) => {
			return d._id === role_type_id1;
		});
		const arr1 = ck_data.map((a) => {
			const role_type_name = a.role_type_name;
			return role_type_name;
		});
		item.role_type_name = arr1[0] ? arr1[0] : '';
		return item;
	});

	const dataArray = dt.map((item: ManagementSanitation) => {
		return Object.assign({}, item, {
			create_time: item.create_time ? format(item.create_time, 'YYYY-MM-DD HH:MM:ss') : '',
			icon: item.icon ? item.icon : ''
		});
	});

	const c = count(action_id, session_id, systemid);
	c.prepare('pub_role', { productid, role_name });
	const [t] = await c.exec();
	return { dataArray, count: t };
}
